import optparse
import sys

import numpy
import tables

from charmicat import BadCommandLineError
import histogram


def adc_hists(ptadc, coords_list=[],
              output='adc_hists.hpt', hname='adc'):
    h = {}

    if len(coords_list) == 0:
        coords_list = [(c,r,ch) for c in xrange(4) 
                       for r in xrange(4) 
                       for ch in xrange(8)]
    else:
        coords_list = [map(int, coords) for  coords in coords_list]

    print coords_list

    for i, coords in enumerate(coords_list):        
        sys.stdout.write("{}/{} hists filled\r".format(i, len(coords_list)))
        sys.stdout.flush()                         

        c, r, ch = coords

        key = '{}{}{}{}'.format(hname, c,r,ch)
        if key not in h:
            h[key] = histogram.Histogram1D(
                key, 
                250,
                (-150, 100),
                'ADC values',
                '',
                title='ADC {}:{}:{}'.format(c,r,ch),
                bufsize=1000)
            
        h[key].fill(ptadc[:,c,r,ch,:,:].flatten())
    
    print "{0}/{0} hists filled\r".format(len(coords_list))

    return histogram.dump(h, output)


def main():    
    '''
    btplot adc_hists [opts] file.h5 

    Histogram the ADC counts for all events in `file.h5'
    '''
    
    op = optparse.OptionParser(usage=main.__doc__)
    
    op.add_option("-c", "--coords", dest='coords_list',
                  action='append',  default=[], 
                  help='Write histograms only for COLROWCHAN' + \
                      ' (one string, can be repeated)',
                  metavar='COLROWCHAN')
    op.add_option("--hname", dest='hname', default='', 
                  help='Give histograms name NAME[col][row][ch]',
                  metavar='NAME')
    op.add_option("-o", "--output-tag", dest='output', default='adc_hists.hpt',
                  help='Write output to PATH.hpt', 
                  metavar='PATH.hpt')

    opts, args = op.parse_args()

    if len(args) == 0:
        msg = "Please supply a PyTables file as input."
        raise BadCommandLineError(msg, -1)

    with tables.openFile(args[0]) as fp:
        adc_hists(fp.root.adc, **vars(opts))


if __name__ == '__main__':
    try:
        import sys
        sys.exit(main())
    except BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)



            
